package com.zhenmaitang.clinic_sys.service.impl;

import com.zhenmaitang.clinic_sys.common.AuthResultCode;
import com.zhenmaitang.clinic_sys.dto.LoginRequest;
import com.zhenmaitang.clinic_sys.dto.UserRegistrationRequest;
import com.zhenmaitang.clinic_sys.entity.Role;
import com.zhenmaitang.clinic_sys.entity.User;
import com.zhenmaitang.clinic_sys.entity.UserRole;
import com.zhenmaitang.clinic_sys.exception.BusinessException;
import com.zhenmaitang.clinic_sys.mapper.UserMapper;
import com.zhenmaitang.clinic_sys.service.AuthService;
import com.zhenmaitang.clinic_sys.service.RoleService;
import com.zhenmaitang.clinic_sys.service.UserRoleService;
import com.zhenmaitang.clinic_sys.util.JwtUtil;
import com.zhenmaitang.clinic_sys.vo.UserVO;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private UserRoleService userRoleService;

    @Override
    public UserVO login(LoginRequest request) {
        try {
            // 验证用户名和密码
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword())
            );

            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            String accessToken = jwtUtil.generateToken(userDetails);
            String refreshToken = jwtUtil.generateRefreshToken(userDetails);

            // 获取用户信息
            User user = userMapper.findByUsername(userDetails.getUsername());
            if (user == null) {
                throw new BusinessException(AuthResultCode.USER_NOT_FOUND);
            }
            
            // 检查用户是否被禁用
            if (user.getEnabled() == null || !user.getEnabled()) {
                throw new BusinessException(AuthResultCode.ACCOUNT_DISABLED);
            }
            
            // 从user_roles关联表获取用户角色
            List<Role> roles = roleService.getRolesByUserId(user.getId());
            List<String> roleNames = new ArrayList<>();
            for (Role role : roles) {
                roleNames.add(role.getName());
            }
            
            UserVO userVO = new UserVO();
            userVO.setUsername(user.getUsername());
            userVO.setFullname(user.getFullName());
            userVO.setRole(roleNames);
            userVO.setAccessToken(accessToken);
            userVO.setRefreshToken(refreshToken);
            userVO.setExpiresIn(3600);
            return userVO;
        } catch (org.springframework.security.core.AuthenticationException e) {
            // 用户名或密码错误
            throw new BusinessException(AuthResultCode.INVALID_CREDENTIALS);
        } catch (Exception e) {
            // 其他异常
            throw new BusinessException(AuthResultCode.SERVICE_UNAVAILABLE, e.getMessage());
        }
    }
    
    
    @Override
    public UserVO register(UserRegistrationRequest request) {
        // 检查用户名是否已存在
        if (userMapper.existsByUsername(request.getUsername())) {
            throw new BusinessException(AuthResultCode.USERNAME_EXISTS);
        }
        
        // 检查邮箱是否已存在
        if (userMapper.existsByEmail(request.getEmail())) {
            throw new BusinessException(AuthResultCode.EMAIL_EXISTS);
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword())); // 直接加密密码
        user.setEmail(request.getEmail());
        user.setFullName(request.getFullName());
        user.setEnabled(true); // 默认启用
        
        userMapper.insert(user);
        
        // 插入后user对象已经包含了生成的ID
        
        // 处理用户角色，通过user_roles关联表管理
        List<String> roleNames = new ArrayList<>();
        if (request.getRole() == null || request.getRole().isEmpty()) {
            // 默认设置USER角色
            roleNames.add("USER");
        } else {
            roleNames = request.getRole();
        }
        
        // 根据角色名称创建用户角色关联
        for (String roleName : roleNames) {
            try {
                Role role = roleService.getRoleByName(roleName);
                UserRole userRole = new UserRole(user.getId(), role.getId(), user.getDepartmentId());
                userRoleService.createUserRole(userRole);
            } catch (Exception e) {
                // 角色不存在，跳过该角色
                continue;
            }
        }
        
        // 生成token
        // 转换角色列表为数组
        String[] roleArray = roleNames.toArray(new String[0]);
        UserDetails userDetails = org.springframework.security.core.userdetails.User
                .withUsername(user.getUsername())
                .password(user.getPassword())
                .roles(roleArray)
                .build();
        String accessToken = jwtUtil.generateToken(userDetails);
        String refreshToken = jwtUtil.generateRefreshToken(userDetails);
        
        UserVO userVO = new UserVO();
        userVO.setUsername(user.getUsername());
        userVO.setFullname(user.getFullName());
        userVO.setRole(roleNames);
        userVO.setAccessToken(accessToken);
        userVO.setRefreshToken(refreshToken);
        userVO.setExpiresIn(3600);
        return userVO;
    }
}